import {StrUtil} from '../../utils/StrUtil.js';

/**
 * 扁平化发布单的应用与插件
 * @param {Array} appAndBranchData
 * @returns {Array<object>}
 */
export function flattenFlowApps(appAndBranchData = []) {
    const result = [];
    if (!Array.isArray(appAndBranchData)) {
        return result;
    }
    for (const item of appAndBranchData) {
        if (!item?.app) {
            continue;
        }
        result.push({
            appName: item.app,
            flowAppId: item.id ?? item.app_id ?? null,
            isPlugin: false,
            parentApp: null,
            isCr: item.is_cr === true,
            lastCommitHasBuild: item.last_commit_has_build === true,
            raw: item
        });
        if (Array.isArray(item.plugin_list)) {
            for (const plugin of item.plugin_list) {
                if (!plugin?.app) {
                    continue;
                }
                result.push({
                    appName: plugin.app,
                    flowAppId: plugin.id ?? plugin.app_id ?? null,
                    isPlugin: true,
                    parentApp: item.app,
                    isCr: plugin.is_cr === true,
                    lastCommitHasBuild: plugin.last_commit_has_build === true,
                    raw: plugin
                });
            }
        }
    }
    return result;
}

/**
 * 轮询等待条件满足
 * @param {function(): Promise<boolean>} checkFn
 * @param {object} options
 * @param {number} [options.timeoutMs=600000]
 * @param {number} [options.intervalMs=5000]
 * @returns {Promise<void>}
 */
export async function waitForCondition(checkFn, {timeoutMs = 600_000, intervalMs = 5_000} = {}) {
    const start = Date.now();
    while (true) {
        const ok = await checkFn();
        if (ok) {
            return;
        }
        if (Date.now() - start > timeoutMs) {
            throw new Error('等待超时');
        }
        await new Promise(resolve => setTimeout(resolve, intervalMs));
    }
}

/**
 * 检查 CR 数据是否通过
 * @param {object} crEntry
 * @returns {boolean}
 */
export function isCrLabelApproved(crEntry) {
    if (!crEntry || typeof crEntry !== 'object') {
        return false;
    }
    if (!Array.isArray(crEntry.labels)) {
        return false;
    }
    return crEntry.labels.some(label => label?.name === '1.CR通过');
}

/**
 * 标准化配置值（读取 properties 时自动 trim）
 * @param {string|undefined|null} value
 * @returns {string}
 */
export function normalizeConfigValue(value) {
    if (StrUtil.isNull(value)) {
        return '';
    }
    return String(value).trim();
}

/**
 * 解析布尔型配置
 * @param {string} value
 * @param {boolean} defaultValue
 * @returns {boolean}
 */
export function parseBoolean(value, defaultValue) {
    if (StrUtil.isNull(value)) {
        return defaultValue;
    }
    const normalized = String(value).trim().toLowerCase();
    if (['true', '1', 'yes', 'y'].includes(normalized)) {
        return true;
    }
    if (['false', '0', 'no', 'n'].includes(normalized)) {
        return false;
    }
    return defaultValue;
}
